const redis = require('./redis');
const crypto = require('crypto');

function User(obj) {
    for (let key in obj) {
        this[key] = obj[key];
    }
}

User.prototype.asyncSave = async function () {
    if (this.id) {
        this.update();
    } else {

        //会判断返回值是否是一个error，如果是就返回error，不是就按流程来
        //以下异步处理都是这么写
        let result = await redis.asyncRedisIncr('user:ids');
        if (result instanceof Error) { return result; }
        this.id = result;

        this.password = User.hashPassword(this.password);

        let result2 = await this.asyncUpdate();
        if (result2 instanceof Error) { return result; }

        return true;
    }
}

User.prototype.asyncUpdate = async function () {
    let result = await redis.sayncRedisSet(`user:data:${this.id}`, JSON.stringify(this));
    if (result instanceof Error) { return result };

    let result2 = await redis.sayncRedisSet(`user:id:${this.account}`, this.id);
    if (result2 instanceof Error) { return result };

    return true;
}

User.hashPassword = function (password) {
    return crypto.createHash('sha256').update(password).digest('hex');
}

User.asyncisExistAccount = async function (account) {
    let result = await redis.sayncRedisGet(`user:id:${account}`);
    //redis返回null意味着没找到,存在返回ture 不存在返回false
    return result === null ? false : true;
}

User.asyncGetIdByAccount = async function (account) {
    return await redis.sayncRedisGet(`user:id:${account}`);
}

User.asyncGetDataById = async function (id) {
    return JSON.parse(await redis.sayncRedisGet(`user:data:${id}`));
}

User.asyncGetAvatarById = async function (id) {
    let result = (await this.asyncGetDataById(id));
    if (result instanceof Object) {
        return result.avatarFileName || null;
    }
    return null;
}

User.asyncGetaccountById = async function (id) {
    let result = (await this.asyncGetDataById(id));
    if (result instanceof Object) {
        return result.account || null;
    }
    return null;
}

//下面都是订阅的api
User.sayncGetUserSubscribe = async function (userId) {
    return JSON.parse(await redis.sayncRedisGet(`user:subscribe:${userId}`));
}

User.asyncIsSubscribeTopic = async function (userId, tobicId) {
    let subscibeArr = await User.sayncGetUserSubscribe(userId);
    if (subscibeArr == null) {
        return false;
    }

    return subscibeArr.includes(tobicId);
}

User.asyncAddSubscribe = async function (userId, tobicId) {
    //如果已经订阅就无需订阅了，直接跳过
    if (!await this.asyncIsSubscribeTopic(userId, tobicId)) {
        let subscibeArr = await this.sayncGetUserSubscribe(userId);

        if (subscibeArr == null) {
            subscibeArr = [];
        }

        subscibeArr.push(tobicId);
        await redis.sayncRedisSet(`user:subscribe:${userId}`, JSON.stringify(subscibeArr));
        return true;
    }
    return false;
}

User.sayncDeleteSubscribe = async function (userId, deleteId) {
    //有了才删，没有不删哦
    if (await this.asyncIsSubscribeTopic(userId, deleteId)) {
        let subscibeArr = await this.sayncGetUserSubscribe(userId);
        let newSubscibeArr = []
        for (let i in subscibeArr) {
            if (i != deleteId) {
                newSubscibeArr.push(i);
            }
        }

        await redis.sayncRedisSet(`user:subscribe:${userId}`, JSON.stringify(newSubscibeArr));
        return true;
    }
    return false;
}



module.exports = User;